#include "gameinterface.h"
#include "ui_gameinterface.h"
#include <QPainter>
#include <windows.h>
#include "logical.h"
#include "game.h"
#define MAX = 5000;

GameInterface::GameInterface(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::GameInterface)
{
    ui->setupUi(this);

    setWindowFlags(Qt::FramelessWindowHint);

    DatabaseMysql *ds = new DatabaseMysql();
    db = ds->db;
    query = ds->query;
//    mcs = new QSound(":/music/backgroundmusic2.wav");
//    mcs->play();

//    ui->textBrowsers->installEventFilter(this);
    mouseSelorder=0;
    idGrade=0;
    //gemtype="gem";
    for(int i=0;i<8;i++){
        for(int j=0;j<8;j++){
            choosen[i][j]=0;//初始化为未被选中
            midBoomS[i][j]=0;//状态为0
        }
    }
    for(int i=0;i<2;i++){
        for(int j=0;j<2;j++){
            gamelogic->swaPoint[i][j]=-1;
        }
    }
    QString path;
    QString path2;
    int i;
     if(game::refh == 0){
        for(i=0;i<8;i++)
        {
            path = ":/images/QS"  + QString::number(i+1,10) + ".png";//宝石图片
            xxlPic[i].load(path);
        }
     }else{
         int j;
         for(j = 0; j < 8; j++){
             path2 = ":/images/Pic" + QString::number(j+1, 10) + ".png";//更新后的宝石图片
             xxlPic[j].load(path2);
         }
     }

    background.load(":/images/background.png");
    background2.load(":/images/backgroundnew2.png");
    selectionBox.load(":/images/select.png");//被选中显示
    explosionProcess1.load(":/images/boom1.png");
    explosionProcess2.load(":/images/boom2.png");
    explosionProcess3.load(":/images/boom3.png");//爆炸过程


    ui->GameInterface::lcdtime3->display(QDateTime::currentDateTime().toString("02"));//初始化时间以及三个lcd中的样式
    ui->GameInterface::lcdtime2->display(QDateTime::currentDateTime().toString("00"));
    ui->GameInterface::lcdMid->display(":");
    ui->GameInterface::lcdtime3->setDigitCount(2);
    ui->GameInterface::lcdtime2->setDigitCount(2);
    ui->GameInterface::lcdMid->setDigitCount(1);
        timer = new QTimer(this);
        timer->setInterval(1000);
            connect(timer, SIGNAL(timeout()), this, SLOT(subTime()));
            connect(ui->btn_Start, SIGNAL(clicked()), this, SLOT(start()));
            //connect(mediaObject,signal(finish(),this,slot(MusicOn()))) ;
}

GameInterface::~GameInterface()
{
    delete ui;
}

void GameInterface::on_btn_Start_clicked()
{
    //setMouseTracking(true);            //设置鼠标跟踪
    p->setWindowFlags(p->windowFlags() | Qt::WindowStaysOnTopHint);//令暂停界面置顶
    if (clicked == false){//切换按钮上的文字，并开始倒计时
        ui->btn_Start->setText(QString("暂停"));
        timer->start(1000);
        clicked = true;
        pu = true;
        fob = true;
        p->hide();
    }
    else if(clicked == true){//暂停倒计时
        ui->btn_Start->setText(QString("开始"));
        timer->stop();
        clicked = false;
        fob = false;
        if(pu == true){
            p->show();
            //ui-> ->setAttribute(Qt::WA_TransparentForMouseEvents, true); //（失能，鼠标点击不响应）
            //p->textBrowser->append(QString("点击开始开始游戏..."));
        }
    }
}

void GameInterface::subTime()
{
    if(m_time > 0)
    {
    m_time--;
    showTime(m_time);
    }else{
        //m_time = 0;//时间结束时就不再变化
        gameOVER();
        ui->GameInterface::lcdtime3->display(QDateTime::currentDateTime().toString("02"));//初始化时间以及三个lcd中的样式
        ui->GameInterface::lcdtime2->display(QDateTime::currentDateTime().toString("00"));
        ui->GameInterface::lcdMid->display(":");
        ui->btn_Start->setText(QString("开始"));
        timer->stop();
        clicked = false;
        fob = false;
        m_time = 120;
        idGrade = 0;
    }
}

void GameInterface::showTime(const unsigned int time_in_s)
{
    int m = m_time / 60;//分钟的计算
    int s = m_time % 60;//秒的计算
    ui->lcdtime3->display(m % 10);
    ui->lcdtime2->display(s);
    if(idGrade>1000&&idGrade<2000&&first==false){
         gemnums=6;
         first=true;
         gamelogic->buildMap(gemnums);
         this->repaint();
    }
    else if(idGrade>2000&&idGrade<4000&&second==false){
         gemnums=7;
         second=true;
         gamelogic->buildMap(gemnums);
         this->repaint();
    }
    else if(idGrade>4000&&third==false){
         gemnums=8;
         third=true;
         gamelogic->buildMap(gemnums);
         this->repaint();
    }
}

void GameInterface::on_btn_Tips_clicked()
{
    if(fob == true){
        if(tips > 0){
        gamelogic->hint();//这里更新了point[2][2]数组
        this->repaint();
        tips--;
        }
        if(tips == 0){
            QMessageBox::information(NULL, NULL,  "提示次数已用完！！");
        }
    }
}

void GameInterface::on_btn_exit_clicked()
{
      exit(0);
}



//int GameInterface::voc = 0;//在类中申明静态变量，记录每一次变换
//void GameInterface::on_pushButton_clicked()//音量键
//{
//    if(voc == 0){
//        //第一次按下按钮时图标变为静音图标
//    ui->GameInterface::pushButton->setStyleSheet("QPushButton{border-image:url(:/images/jingyin.png)}");
//    //mcs->stop();
//    //this->mcs->stop();
//    voc = 1;
//    }
//        else{
//            ui->GameInterface::pushButton->setStyleSheet("QPushButton{border-image:url(:/images/sound.png)}");
//    //mcs->play();
//            voc = 0;//第二次按下按钮时再次变换图标
//    }
//}

void GameInterface::paintEvent(QPaintEvent *event)//画被选中框，宝石图片，提示框，消除的中间过程，加分动画
{

    QPainter painter(this);
    int num;
//    if(game::refh == 0){
    painter.drawPixmap(0,0,width(),height(),background);
//    }else
//        painter.drawPixmap(0,0,width(),height(),background2);
    //画被选中框，宝石图片，提示框，消除的中间过程，加分动画
    for(int i=0;i<8;i++){
        QString temp="";
        for(int j=0;j<8;j++){
            num=gamelogic->gemstNcord[i][j];
            temp+=QString::number(num);
//            painter.drawPixmap(20+j*50,50+i*50,50,50,pixmap[num-1]);
            painter.drawPixmap(275+j*63,50+i*61,60,60,xxlPic[num-1]);

            if(choosen[i][j]==1){//被选中的框
                painter.drawPixmap(275+j*63,50+i*61,60,60, selectionBox);
                choosen[i][j]=0;
            }
            if(i==gamelogic->swaPoint[0][0]&&j==gamelogic->swaPoint[0][1]){//提示的框
                painter.drawPixmap(275+j*63,50+i*61,60,60, selectionBox);
                gamelogic->swaPoint[0][0]=gamelogic->swaPoint[0][1]=-1;//初始化
            }
            if(i==gamelogic->swaPoint[1][0]&&j==gamelogic->swaPoint[1][1]){
                painter.drawPixmap(275+j*63,50+i*61,60,60, selectionBox);
                gamelogic->swaPoint[1][0]=gamelogic->swaPoint[1][1]=-1;//初始化
            }
            //midSituation是消除的中间过程
            if(midBoomS[i][j]==1){
                painter.drawPixmap(275+j*63,50+i*61,60,60,explosionProcess1);
            }else if(midBoomS[i][j]==2){
                painter.drawPixmap(275+j*63,50+i*61,60,60,explosionProcess2);
            }else if(midBoomS[i][j]==3){
                painter.drawPixmap(275+j*63,50+i*61,60,60,explosionProcess3);
                midBoomS[i][j]=0;
          }

        }
    }

//        QPainter painter2(this);
//        int num;
//        painter2.drawPixmap(0,0,width(),height(),background2);
//        //画被选中框，宝石图片，提示框，消除的中间过程，加分动画
//        for(int i=0;i<8;i++){
//            QString temp="";
//            for(int j=0;j<8;j++){
//                num = gamelogic->gemstNcord[i][j];
//                temp+=QString::number(num);
//    //            painter.drawPixmap(20+j*50,50+i*50,50,50,pixmap[num-1]);
//                painter2.drawPixmap(275+j*63,50+i*61,60,60,xxlPic2[num-1]);

//                if(choosen[i][j]==1){//被选中的框
//                    painter2.drawPixmap(275+j*63,50+i*61,60,60, selectionBox);
//                    choosen[i][j]=0;
//                }
//                if(i==gamelogic->swaPoint[0][0]&&j==gamelogic->swaPoint[0][1]){//提示的框
//                    painter2.drawPixmap(275+j*63,50+i*61,60,60, selectionBox);
//                    gamelogic->swaPoint[0][0]=gamelogic->swaPoint[0][1]=-1;//初始化
//                }
//                if(i==gamelogic->swaPoint[1][0]&&j==gamelogic->swaPoint[1][1]){
//                    painter2.drawPixmap(275+j*63,50+i*61,60,60, selectionBox);
//                    gamelogic->swaPoint[1][0]=gamelogic->swaPoint[1][1]=-1;//初始化
//                }
                //midSituation是消除的中间过程
//                if(midBoomS[i][j]==1){
//                    painter2.drawPixmap(275+j*63,50+i*61,60,60,explosionProcess1);
//                }else if(midBoomS[i][j]==2){
//                    painter2.drawPixmap(275+j*63,50+i*61,60,60,explosionProcess2);
//                }else if(midBoomS[i][j]==3){
//                    painter2.drawPixmap(275+j*63,50+i*61,60,60,explosionProcess3);
//                    midBoomS[i][j]=0;
//              }

//            }
//        }
//    }
}
void GameInterface::closeEvent(QCloseEvent *event)//Game Over 函数
{

}

void GameInterface::Game_start(){

    gamelogic->buildMap(gemnums);  //初始化游戏地图

    this->repaint(); //画被选中框，宝石图片，提示框，消除的中间过程，加分动画
}


//bool MainWindow::eventFilter(QObject *watched, QEvent *event)
//{
//    if(watched ==ui->textBrowsers&&event->type()==QEvent::Paint)
//    {
//        paintEvent(ui->textBrowsers);
//    }else if(watched ==ui->textBrowsers&&event->type() == QEvent::MouseButtonPress){
//        QMouseEvent * mouseEvent=static_cast<QMouseEvent*>(event);
//        mousePressEvent(mouseEvent);
//    }
//    return QWidget::eventFilter(watched,event);
//}

void GameInterface::mousePressEvent(QMouseEvent *ev){

    if(fob==true){
    int eli_number=0;

    QPainter painter(this);
    mouseflag=1;
    int xx;
    int yy;
    xx=ev->x()-276;
    yy=ev->y()-50;
    mouseSelY=xx/60;
    mouseSelX=yy/60;//把点击的坐标翻译成了宝石矩阵的行列号，便于下面访问算法
    if(0<=mouseSelX&&mouseSelX<8&&mouseSelY>=0&&mouseSelY<8){//仅在8*8宝石范围内相应鼠标点击事件
            if(mouseSelorder==0){
                mouseSelection1.setX(mouseSelX);
                mouseSelection1.setY(mouseSelY);//存下了第一次点击的横纵坐标（换算后的，可以直接用来访问矩阵）
                choosen[mouseSelX][mouseSelY]=1;
                mouseSelorder=1;
                this->repaint();//其实是调用了paintevent
            }

            int x=mouseSelection1.x();
            int y=mouseSelection1.y();//取得第一次点击的横纵坐标与新的坐标相比较
            choosen[mouseSelX][mouseSelY]=1;
            this->repaint();
            //painter.drawPixmap(20+focus_y*50,50+focus_x*50,50,50,pixmap_di);

            if((mouseSelX==x && (mouseSelY==y-1 || mouseSelY==y+1)) || (mouseSelY == y && (mouseSelX==x-1 || mouseSelX==x+1))){//相邻情况（上下左右）==边界？？？
                mouseSelection2.setX(mouseSelX);
                mouseSelection2.setY(mouseSelY);//把第二次的坐标也存下了，便于后面访问
                mouseSelorder = 0;//标志

                int temp;
                temp=gamelogic->gemstNcord[x][y];
                gamelogic->gemstNcord[x][y]=gamelogic->gemstNcord[mouseSelX][mouseSelY];
                gamelogic->gemstNcord[mouseSelX][mouseSelY]=temp;
                this->repaint();
                _sleep(100);
                if(!gamelogic->eliminate())//点的两个不能交换//eliminate返回
                {
                    //换回来
                    int temp1;
                    temp1=gamelogic->gemstNcord[x][y];
                    gamelogic->gemstNcord[x][y]=gamelogic->gemstNcord[mouseSelX][mouseSelY];
                    gamelogic->gemstNcord[mouseSelX][mouseSelY]=temp1;
                    this->repaint();
                    _sleep(100);

                }
                while (gamelogic->eliminate()){//只要能消除
                    eliminateNumber = 0;
                    for(int i = 0; i < 8; i++){
                        for(int j = 0; j < 8; j++)
                        {
                            if(gamelogic->gemstNcord[i][j] == 0)
                            {
                                eliminateNumber++;//这个是0的个数 消除数
                                midBoomS[i][j]=1;//状态1
                            }
                        }
                    }
                    eli_number += eliminateNumber;
                    if (eli_number == 3) {
                        idGrade += eli_number * 10;//消除一个十分；
                    } else {
                        idGrade += eli_number * 20;//三消以上一个二十分;
                    }
                    ui->label->setText(QString("当前得分：\n") + QString("%1").arg(idGrade));
                    //消除宝石的音效



                    this->repaint();
                    _sleep(100);
                    for(int i = 0; i < 8; i++){
                        for(int j = 0; j < 8; j++)
                        {
                            if(gamelogic->gemstNcord[i][j] == 0)
                            {
                                //更换图片
                                midBoomS[i][j]=2;//状态2

                            }
                        }
                    }
                    this->repaint();
                    _sleep(100);
                    for(int i = 0; i < 8; i++){
                        for(int j = 0; j < 8; j++)
                        {
                            if(gamelogic->gemstNcord[i][j] == 0)
                            {
                                //更换图片
                                midBoomS[i][j]=3;//状态3
                            }
                        }
                    }

                    this->repaint();
                    _sleep(100);
                    for(int k=0;k<10;k++){
                        addScoreSituation=k;
                        this->repaint();
                        _sleep(25);
                    }

                    while(gamelogic->down()){

                        this->repaint();//消完一次后下移，并重画，有下移音效
//                        QSound::play(":/music/soundeffect1.wav");
                        _sleep(100);
                    }
                }

            }
            else{
                mouseSelection1.setX(mouseSelX);
                mouseSelection1.setY(mouseSelY);
            }

            if(!gamelogic->hint())//当前整个地图没有可以交换产生三连->重新构图
            {
                gamelogic->buildMap(gemnums);
                this->repaint();
            }
            else//复原因为调用hint而改变的提示框位置
            {
                gamelogic->swaPoint[0][0] = -1;
                gamelogic->swaPoint[0][1] = -1;
                gamelogic->swaPoint[1][0] = -1;
                gamelogic->swaPoint[1][1] = -1;
            }
    }
  }
}

void GameInterface::gameOVER(){
    QMessageBox::information(NULL, "游戏结束", "时间到，游戏结束");
    QString qstr = QString::fromStdString(ID);
    QString sss=QString::number(idGrade,10);
        QString str = QString("UPDATE `users` SET `score` = '%1' WHERE `username` = '%2'").arg(idGrade).arg(qstr);
        //qDebug()<<query.exec(str);

        if(query.exec(str))
             qDebug()<<"socre success!"<<Qt::endl;
        else  qDebug()<<"socre not success!"<<Qt::endl;

}

void GameInterface::on_pushButton_2_clicked()//返回开始界面
{
    if(fob == true){
    this->close();
    game *g = new game;
    g->show();
    }else
    {
        p->close();
        this->close();
        game *g = new game;
        g->show();
    }
}
